package com.ks.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.ks.entity.User;
import com.ks.utils.JDBCUtil;

public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {
	public static void main(String[] args) {
		UserDaoImpl userDaoImpl = new UserDaoImpl();
		User user = userDaoImpl.selectOneUser("admin");
		System.out.println(user.getUsername());
		List<User> uList =userDaoImpl.selectUserByCondition(new Object[] {"'17','18'"});
		System.out.println(uList.size());
	}

	@Override
	public User selectOneUser(String name) {
		String sql = "SELECT * FROM T_USER WHERE USERNAME =?";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;// 定义存放查询结果的结果集
		User user = null;
		try {
			conn = JDBCUtil.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, name);
			rs = pstmt.executeQuery();// 运行查询操作
			if (rs.next()) {
				user = new User();
				user.setUsername(rs.getString("userName"));
				user.setPassword(rs.getString("password"));
				user.setAge(rs.getInt("age"));
				user.setAddress(rs.getString("address"));
				user.setImg(rs.getString("img"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 按顺序进行关闭
			JDBCUtil.closeResultSet(rs);
			JDBCUtil.close(pstmt, conn);

		}
		return user;
	}

	@Override
	public List<User> excuteQuery(String sql, Object[] obj) {
		return new ArrayList<>();
	}

	@Override
	public List<User> selectAllUser() {
		String sql = "SELECT USERNAME,PASSWORD,AGE,ADDRESS,IMG FROM T_USER ";
		return executeQuery(sql);
	}

	@Override
	public List<User> selectUserByCondition(Object[] condition) {
		String sql = "SELECT USERNAME,PASSWORD,AGE,ADDRESS,IMG FROM T_USER WHERE USERID IN(?)";
		return executeQuery(sql,condition);
	}

	@Override
	public int selectCount() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int insertOneUser(User user) {
		String sql = "INSERT INTO T_USER(USERID,USERNAME,PASSWORD,AGE,ADDRESS,IMG)VALUES(SEQ_USER_ID.Nextval,?,?,?,?,?)";
		Object[] obj = new Object[] { user.getUsername(), user.getPassword(), user.getAge(), user.getAddress(),
				user.getImg() };
		return executeUpdate(sql, obj);
	}

	@Override
	public int updateOneUser(User user) {
		String sql = "UPDATE T_USER SET PASSWORD=?,AGE=?,ADDRESS=?,IMG=? WHERE USERNAME=? ";
		Object[] obj = new Object[] { user.getPassword(), user.getAge(), user.getAddress(), user.getImg(),
				user.getUsername() };
		return executeUpdate(sql, obj);
	}

	@Override
	public int deleteOneUser(String username) {
		String sql = "DELETE FROM  T_USER WHERE USERNAME =?";
		return executeUpdate(sql, new Object[] { username });
	}

}
